import { formatUrl } from '../utils/utils'

export let navigator = {
  urlBase: '',
  url: {},
  route: {
    home: '/pages/home/home',
    login: '/pages/auth/login',
    personal: '/pages/personal/personal',
  },

  current() {
    let pages = getCurrentPages()
    return pages[pages.length-1]
  },

  push(url, params) {
    return uni.navigateTo({
      url: formatUrl(url, params)
    }).then(([err, res])=>{
      if(err) return Promise.reject(err)
      return res
    })
  },
  replace(url, params) {
    return uni.redirectTo({
      url: formatUrl(url, params)
    }).then(([err, res])=>{
      if(err) return Promise.reject(err)
      return res
    })
  },
  back(delta=1, failToRelaunch=true) {
    if(failToRelaunch&&delta>=getCurrentPages().length) {
      navigator.relaunch()
      return
    }
    // #ifndef XT_PC
    return uni.navigateBack({
      delta
    });
    // #endif
    
    // #ifdef XT_PC
    return window.history.back()
    // #endif
  },

  switchTab(url, params) {
    return uni.switchTab({
      url: formatUrl(url, params)
    }).then(([err, res])=>{
      if(err) return Promise.reject(err)
      return res
    })
  },
  relaunch(url, params) {
    if(url===undefined) {
      if(uni.$x.app.relaunchHome) {
        url = navigator.route.home || '/'
      }else{
        url = '/'+uni.$x.app.path
        params = uni.$x.app.query
      }
    }else if(url===true) {
      let page = getCurrentPages()[getCurrentPages().length-1]
      url = '/'+(page?page.route:'')
      params = page?page.options:{}
    }
    
    return uni.reLaunch({
      url: formatUrl(url, params||{})
    }).then(([err, res])=>{
      if(err) return Promise.reject(err)
      return res
    })
  },

  goHome(url=navigator.route.home) {
    // #ifndef XT_PC
    return uni.switchTab({
      url
    })
    // #endif
    // #ifdef XT_PC
    return uni.navigateTo({
      url
    })
    // #endif
  },
  goLogin(url=navigator.route.login, params={}) {
    uni.$x.layout.splashHide()
    if(!getCurrentPages()||'/'+getCurrentPages()[getCurrentPages().length-1].route===url) return
    // console.log('goLogin', url, getCurrentPages()[getCurrentPages().length-1].route, getCurrentPages()[getCurrentPages().length-1].route==='/'+url)
    uni.navigateTo({
      url: formatUrl(url, params)
    }).then((err, res)=>{
      if(err) return Promise.reject(err)
      return res
    })
  },
  goPersonal(url=navigator.route.personal) {
    return uni.switchTab({
      url
    }).then((err, res)=>{
      if(err) return Promise.reject(err)
      return res
    })
  }
}


export default function($x, {
	navigatorRouteExtend, navigatorExtend
}={}, app) {
	Object.assign(navigator, navigatorExtend||{})
	Object.assign(navigator.route, navigatorRouteExtend||{})
	$x.navigator = navigator
}